<link rel="stylesheet" href="component/assets/css/bootstrap-duallistbox.css" />
<link rel="stylesheet" href="component/assets/css/select2.css" />
<style type="text/css">
.ui-jqgrid-sortable {
	text-align: center;
}
</style>

<div id="proprietor_container">
	<div class="row">
		<div class="col-xs-12">



			<table id="proprietor_grid-table"></table>

			<div id="proprietor_grid-pager"></div>

		</div>
		<!-- /.col -->
	</div>
	<!-- /.row -->


	<div id="proprietorModalDiv" class="modal fade" tabindex="-1"
		data-backdrop="static">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header no-padding">
					<div class="table-header">
						<button type="button" class="close" data-dismiss="modal"
							aria-hidden="true">
							<span class="white">&times;</span>
						</button>
						<span id="dialogTitle">添加业主</span>
					</div>
				</div>
				<div class="modal-body"
					style="max-height: 450px; overflow-y: scroll;">
					<div id="modal-tip" class="red clearfix"></div>
					<form id="proprietorForm" name="proprietorForm"
						class="form-horizontal  col-xs-12">
						<div class="widget-box  ui-sortable-handle">
							<div class="widget-header">
								<h4 class="widget-title">基本信息</h4>
							</div>
							<div class="widget-body">
								<input type="hidden" name="id" id="id" /> <input type="hidden"
									name="files" id="proprietorfiles" />
								<div class="widget-main">
									<div class="row" style="padding-bottom: 2px">
										<div class="form-group">
											<label class="col-sm-3 control-label">姓名</label>
											<div class="col-sm-9">
												<input type="text" class="form-control" id="name"
													name="name" />
											</div>
										</div>
									</div>
									<div class="row" style="padding-bottom: 2px">
										<div class="form-group">
											<label class="col-sm-3 control-label">性别</label>
											<div class="col-sm-9">
												<select class="form-control" id="gender" name="gender">
													<option value="1">男</option>
													<option value="2">女</option>
												</select>
											</div>
										</div>
									</div>
									<div class="row" style="padding-bottom: 2px">
										<div class="form-group">
											<label class="col-sm-3 control-label">电话号码</label>
											<div class="col-sm-9">
												<input type="text" class="form-control" id="phone"
													name="phone" />
											</div>
										</div>
									</div>
									<div class="row" style="padding-bottom: 2px">
										<div class="form-group">
											<label class="col-sm-3 control-label">身份证号</label>
											<div class="col-sm-9">
												<input type="text" class="form-control" id="identityCard"
													name="identityCard" />
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="row" style="padding-bottom: 2px;">
							<div class="col-xs-12">
								<div class="widget-box  ui-sortable-handle">
									<div class="widget-header">
										<h4 class="widget-title">身份证信息</h4>
										<div class="widget-toolbar">
											<a href="#" title="添加图片" data-action="settings"> <i
												class="1 ace-icon fa bigger-125  fa-cloud-upload fileinput-button"></i>
											</a>
										</div>
									</div>
									<div class="widget-body">
										<div class="widget-main">
											<div class="dropzone" id="proprietordropzone"></div>
										</div>
									</div>
								</div>
							</div>
						</div>

					</form>

				</div>
				<div class="modal-footer no-margin-top">
					<div class="text-center">

						<button id="submitProprietorBtn" class="btn btn-sm btn-primary">
							<i class="ace-icon fa fa-floppy-o"></i> <span>保存</span>
						</button>

						<button class="btn btn-sm" data-dismiss="modal">
							<i class="ace-icon fa fa-share "></i> <span>取消</span>
						</button>
					</div>
				</div>
			</div>
		</div>
		<!-- /.modal-content -->

		<div id="proprietorpreview-template" style="display: none">
			<div class="dz-preview dz-file-preview">
				<div class="dz-details">
					<div class="dz-filename">
						<span data-dz-name></span>
					</div>
					<div class="dz-size" data-dz-size></div>
					<a id='' href='#' class="image-see" data-rel='colorbox'><img
						data-dz-thumbnail /> </a>
				</div>
				<div class="dz-progress">
					<span class="dz-upload" data-dz-uploadprogress></span>
				</div>
				<div class="dz-success-mark">
					<span>✔</span>
				</div>
				<div class="dz-error-mark">
					<span>✘</span>
				</div>
				<div class="dz-error-message">
					<span data-dz-errormessage></span>
				</div>
				<div class="center">
					<span data-dz-remove> <a href="#" data-action="delete"
						class="middle"> <i
							class="ace-icon fa fa-trash-o red bigger-130 middle"></i>
					</a>
					</span>
				</div>
			</div>
		</div>
	</div>
	
	<div id="doorplateBindDiv" class="modal fade" tabindex="-1"
		data-backdrop="static">
		<input type="hidden" id="proprietorId">
		<div class="modal-dialog" style="width: 700px !important;">
			<div class="modal-content">
				<div class="modal-header no-padding">
					<div class="table-header">
						<button type="button" class="close" data-dismiss="modal"
							aria-hidden="true">
							<span class="white">&times;</span>
						</button>
						<span>绑定门牌号</span>
					</div>
				</div>
				<div class="modal-body"
					style="max-height: 500px;height:500px; overflow-y: scroll;">
					<div id="doorplatemodal-tip" class="red clearfix"></div>
					<div style="height:100%">
						<div style="width:640px;height:100%;margin-left:10px;">
							<div class="row">
								<div class="col-xs-12">
									<div id="search_box" class="widget-box  ui-sortable-handle collapsed">
										<div class="widget-header">
											<div class="nav-search" style="padding-top: 12px; left: 25px">
												<span class="input-icon"> 
												<input type="text" id="doorplateNo2" 
													placeholder="请输入门牌号" class="nav-search-input"> 
												<i class="ace-icon fa fa-search nav-search-icon"></i>
												</span>
											</div>
											
											<div class="form-group">
												<div id="select2Div" class="col-xs-12 col-sm-9" style="left:170px;top:8px;">
												</div>
											</div>
											
											<div id="searchDoorplateDiv" class="input-group col-xs-12  col-sm-6  "
												style="width:50px;bottom: 8px;float:right;">
												<span class="input-group-btn">
													<button id="searchDoorplateBtn" type="button"
														class="btn btn-purple btn-sm">
														<span class="ace-icon fa fa-search icon-on-right bigger-110"></span>
														<span i18n="find"></span>
													</button>
												</span>
											</div>
											
										</div>
									</div>
									<div class="form-group">
										<div class="col-sm-8" style="width:650px" id="emptyduallist">
											<!-- #section:plugins/input.duallist -->
											<select multiple="multiple" name="duallistbox_doorplate" id="duallist"
											 style="height:325px;"></select>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer no-margin-top">
					<div class="text-center">

						<button id="submitDoorplateBindBtn" class="btn btn-sm btn-primary">
							<i class="ace-icon fa fa-floppy-o"></i> <span>保存</span>
						</button>

						<button class="btn btn-sm" data-dismiss="modal">
							<i class="ace-icon fa fa-share "></i> <span>取消</span>
						</button>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- /.modal-dialog -->
</div>

<script type="text/javascript">

var proprietorScripts = [ null,"component/assets/js/dropzone.js", 
	"component/assets/js/jquery.colorbox.js", "component/assets/js/select2.js",
	"component/assets/js/jquery.bootstrap-duallistbox.js",null ];
var $proprietorContainer = $('#proprietor_container');
var proprietorGrid = null;
var $validateProprietorForm = null;
var doorplateContainer=null;
var doorplateBox=null;
var ProprietorDropzone=null;
var muban=null;

var colorbox_params = {
    rel : 'colorbox',
    reposition : true,
    scalePhotos : true,
    scrolling : false,
    previous : '<i class="ace-icon fa fa-arrow-left"></i>',
    next : '<i class="ace-icon fa fa-arrow-right"></i>',
    close : '&times;',
    current : '{current} of {total}',
    maxWidth : '100%',
    maxHeight : '90%',
    onOpen : function() {
	$overflow = document.body.style.overflow;
	document.body.style.overflow = 'hidden';
    },
    onClosed : function() {
	document.body.style.overflow = $overflow;
    },
    onComplete : function() {
	$.colorbox.resize();
    }
};

$('.page-content-area').ace_ajax('loadScripts', proprietorScripts, function() {
	var grid_selector  = "#proprietor_grid-table";
	var pager_selector = "#proprietor_grid-pager";
	
	var colNames =['',
		'姓名','性别','电话号码' ,'身份证号',
        '操作' 
	];
	createProprietorGrid();
	
	$validateProprietorForm = $('#proprietorForm',$proprietorContainer).validate({
    	onsubmit:false,
    	rules : {
    		name : {
				required : true
			},
			phone : {
				required : true
			},
			identityCard : {
				required : true
			}
		}
    });
	
	$('#submitProprietorBtn').click(function(){
		if(!$validateProprietorForm.checkForm()){
			$validateProprietorForm.defaultShowErrors();
			return;
		}
		var url = $(this).attr("url");
		var fileIds = [];
		var id = $('#id',$("#proprietorForm",$proprietorContainer)).val();
		$('.dropzone [data-rel="colorbox"]').map(function(k, v) {
			fileIds.push(v.id);
	    })
	    $("#proprietorfiles", $proprietorContainer).val(fileIds);
		var message="";
		if(id && id !=""){
			message="确定要修改这条记录吗？"
		}else{
			message="确定要添加一条记录吗？"
		}
		$.loy.confirm(message,function(){
	        $.loy.ajax({
				url:url,
				data:$("#proprietorForm",$proprietorContainer).serialize(),
				success:function(data){
					$('#proprietorModalDiv',$proprietorContainer).modal("hide");
					proprietorGrid.jqGrid().trigger("reloadGrid");
				},
				error : function(data){
					alert("发生错误");
				}
			});  
		});	
    });
	
	$("#submitDoorplateBindBtn").on("click",function(){
		var doorplateIds=$("#duallist").val();
		var ids="";
		var url="";
		var datas="";
		var message="确定要为该用户绑定所选择的门牌号吗？";
		var message2="绑定成功";
		if(doorplateIds==""||doorplateIds==null){
			message="该用户没有选择门牌号，需要执行解绑操作吗？";
			message2="解绑成功";
			url="mp/unbindProprietor";
			datas={
				proprietorId : $("#proprietorId").val()
			}
		}else{
			url="mp/bindProprietor";
			for (var i = 0; i < doorplateIds.length; i++) {
				if(i==0){
					ids+=doorplateIds[i];
				}else{
					ids+=","+doorplateIds[i];
				}
			}
			datas={
				proprietorId : $("#proprietorId").val(),
				ids : ids
			}
		}
		$.loy.confirm(message,function(){
			//为用户绑定门牌号
			$.loy.ajax({
				url : url,
				type : 'POST',
				data : datas,
				success:function(data){
					$.loy.alert(message2);
					$('#doorplateBindDiv', $proprietorContainer).modal("hide");
				},
				error : function(data){
				}
		   });   
	    })
	});
	
	$("#searchDoorplateBtn").on("click",function(){
		var selectData=$("#court").select2("data")
		var str="";
		for (var i = 0; i < selectData.length; i++) {
			if(i==0){
				str+=selectData[i].id;
			}else{
				str+=","+selectData[i].id;
			}
		}
		//查询未被绑定的门牌号相关信息
		$.loy.ajax({
			url : "/mp/searchDoorPlate",
			type : 'GET',
			data : {
				doorplateNo : $.trim($("#doorplateNo2").val()),
				courtId : str
			},
			success : function(data) {
				var result=data.data;
				doorplateBox.bootstrapDualListbox('destroy');
				doorplateBox=null;
				$("#emptyduallist").empty();
			 	var select=$("<select></select>");	
			 	select.css("height","325px");
			 	select.attr({"multiple":"multiple","name":"duallistbox_doorplate","id":"duallist"});
				for (var i = 0; i < result.length; i++) {
					var option=$("<option></option>");
					option.val(result[i].id);
					option.text(result[i].doorplateNo);
					select.append(option);
				}
				//加载已经绑定了的门牌号
				$.loy.ajax({
					url : "/mp/loadBindDoorplate",
					type : 'GET',
					data : {
						proprietorId : $("#proprietorId").val()
					},
					success : function(data) {
						var result=data.data;
						for (var i = 0; i < result.length; i++) {
							var option=$("<option></option>");
							option.val(result[i].id);
							option.text(result[i].doorplateNo);
							option.attr("selected","selected");
							select.append(option);
						}
						$("#emptyduallist").append(select);
						doorplateBox=select.bootstrapDualListbox({
							showFilterInputs:false
						});
						doorplateContainer = doorplateBox.bootstrapDualListbox('getContainer');
						doorplateContainer.find('.btn').addClass('btn-white btn-info btn-bold');
						doorplateBox.bootstrapDualListbox('refresh',true);
					},
					error : function(data){
					}
				})
			},
			error : function(data) {
				alert("查询门牌号发生错误");
			}
	   });
	});
	
	$('#doorplateBindDiv').on('hide.bs.modal', function () {
		$('[class*=select2]').remove();
		doorplateBox.bootstrapDualListbox('destroy');
		doorplateBox=null;
		$("#emptyduallist").empty();
	 	var select=$("<select></select>");	
	 	select.css("height","325px");
	 	select.attr({"multiple":"multiple","name":"duallistbox_doorplate","id":"duallist"});
	 	$("#emptyduallist").append(select);
	})
	
	function  createProprietorGrid(){
		proprietorGrid =jQuery(grid_selector).loyGrid({
			url: 'yz/findAll',
			datatype: "json",
			mtype: 'GET',
			colNames:colNames,
			colModel: [
				{ name: 'id', index: 'id',sortable:false, width: 0, align: "center", editable: true,hidden:true} ,
		   		{ name: 'name', index: 'name',sortable:false, width: 100, align: "center", editable: true} ,
		   		{ name: 'gender', index: 'gender',sortable:false, width: 100, align: "center", 
		   			formatter:function(cellvalue, options, rowObject) {
		   				if(cellvalue==1){
		   					return '男';
		   				}
		   				else if(cellvalue==2){
		   					return '女';
		   				}
		   				else{
		   					return cellvalue;
		   				}
					}
		   		} ,
		   		{ name: 'phone', index: 'phone',sortable:false, width: 150, align: "center", editable: true} ,
		   		{ name: 'identityCard', index: 'identityCard',sortable:false, width: 200, align: "center", editable: true} ,
		   		{ name:'',index:'', width:300, fixed:true, sortable:false, resize:false ,align: "center",
					formatter:function(cellvalue, options, rowObject) {
						var button = '';
						if(hasPermissionByCode('resource:update')){
							button +='<div title="'+$.jgrid.nav.edittitle+'" onclick=proprietorEdit("'+rowObject.id+'");  style="float:left;margin-left:110px;" class="ui-pg-div ui-inline-del"  onmouseover="jQuery(this).addClass(\'ui-state-hover\');" onmouseout="jQuery(this).removeClass(\'ui-state-hover\');"  data-original-title="所选记录"><span class="ui-icon ui-icon-pencil"></span></div>';
						}
						if(hasPermissionByCode('resource:del')){
							var del ='<div title="'+$.jgrid.nav.deltitle+'" onclick=proprietorDel("'+rowObject.id+'");  style="float:left;margin-left:5px;" class="ui-pg-div ui-inline-del"  onmouseover="jQuery(this).addClass(\'ui-state-hover\');" onmouseout="jQuery(this).removeClass(\'ui-state-hover\');"  data-original-title="所选记录"><span class="ui-icon ace-icon ace-icon fa fa-trash-o red"></span></div>';
							button += del;   
						}
						var bindDoorplate= '<div title="'
							+ "绑定门牌号"
							+ '" onclick=bindDoorplate("'
							+ rowObject.id
							+ '");  style="float:left;margin-left:5px;" class="ui-pg-div ui-inline-del"  onmouseover="jQuery(this).addClass(\'ui-state-hover\');" onmouseout="jQuery(this).removeClass(\'ui-state-hover\');"  data-original-title="所选记录"><span class="ui-icon ace-icon fa fa-bell green"></span></div>';
							button += bindDoorplate;
						return button;
					}
				}
			],
			pager : pager_selector,
			width : $(".page-content").width(),
			height : getGridDefaultHeight(),
		    }).loyGrid('navGrid', '#proprietor_grid-pager', {
				"baseUrl" : "yz/",
				accessCodePrefix : 'addyzInfo',
				"addfunc":function(){
					proprietorAdd('');
				},
				view: false,
				add:true,
				edit:false,
				del:false,
				excel:false
		    });
			proprietorGrid.jqGrid('setFrozenColumns');
	}
	
});
function clearProprietorForm(){
	$validateProprietorForm.resetForm();
	$('#id',$proprietorContainer).val('');
	$('#name',$proprietorContainer).val('');
	$('#phone',$proprietorContainer).val('');
	$('#identityCard',$proprietorContainer).val('');
	$('#gender',$proprietorContainer).val('1');
	$('.dz-preview').remove(); 
}
function proprietorEdit (id){
	if(muban==null){
		muban=document.querySelector('#proprietorpreview-template').innerHTML;
	}
	if(ProprietorDropzone!=null){
		ProprietorDropzone.destroy();
	}
	initProprietorDropzone(muban);
	clearProprietorForm();
	$("#dialogTitle").text("修改业主");
	$('#submitProprietorBtn',$proprietorContainer).attr("url","yz/addyzInfo");
	$('#proprietorModalDiv',$proprietorContainer).modal("show");
	$.loy.ajax({
		url:'yz/findOne',
		shade:false,
		data:{id:id},
		success:function(data){
			var result = data.data;
			$('#id',$proprietorContainer).val(result.id?result.id:'');
			$('#name',$proprietorContainer).val(result.name?result.name:'');
			$('#phone',$proprietorContainer).val(result.phone?result.phone:'');
			$('#identityCard',$proprietorContainer).val(result.identityCard?result.identityCard:'');
			$('#gender',$proprietorContainer).val(result.gender?result.gender:'1');
			
			$.loy.ajax({
				url : "/sys/img/getFiles",
				showSuccess : false,
				type : 'GET',
				data : {
				    aId : result.id
				},
				success : function(data) {
				    $.each(data.data, function(index, item) {
						var mockFile = {
						    id : item.id,
						    name : item.medianame,
						    size : item.mediasize,
						    httpurl : item.httpurl
						};
						// Call the default addedfile event handler
						ProprietorDropzone.emit("addedfile", mockFile);
						// And optionally show the thumbnail of the file:
						ProprietorDropzone.emit("thumbnail", mockFile, item.httpurl);
	
				    });
				    
				    $('.dropzone [data-rel="colorbox"]').colorbox(colorbox_params);
				}
		    });
		}
   });
}
function proprietorAdd(){
	if(muban==null){
		muban=document.querySelector('#proprietorpreview-template').innerHTML;
	}
	if(ProprietorDropzone!=null){
		ProprietorDropzone.destroy();
	}
	initProprietorDropzone(muban);
	clearProprietorForm();
	$('#submitProprietorBtn',$proprietorContainer).attr("url","yz/addyzInfo");
	$('#proprietorModalDiv',$proprietorContainer).modal({
		show:true
	});
	$("#dialogTitle").text("添加业主");
}
function proprietorDel(id){
	var that=this;
	$.loy.confirm($.i18n.prop('confirm_info_del'),function(){
		$.loy.ajax({
			url:'yz/delyzInfo',
			data:{id:id},
			success:function(data){
				that.refreshGrid();
			}
	   });   
	});	
}
function bindDoorplate(proprietorId){
	$("#proprietorId").val(proprietorId);
	$("#select2Div").empty();
	var select=$("<select></select>");
	select.attr({
		"multiple" : "multiple",
		"id" : "court",
		"name" : "state",
		"data-placeholder" : "选择小区"
	})
	select.addClass("select2");
	$("#select2Div").append(select);
	$('.select2').css('width','200px').select2({allowClear:true})
	//$('.select2').addClass('tag-input-style');
	//加载小区下拉框
	$.loy.ajax({
		url : "/xq/findAll",
		type : 'GET',
		data : {},
		success : function(data) {
			var result=data.data;
			$("#court").empty();
			for (var i = 0; i < result.length; i++) {
				var option=$("<option></option>");
				option.val(result[i].id);
				option.text(result[i].name);
				$("#court").append(option);
			}
		},
		error : function(data) {
			alert("加载小区列表失败");
		}
   });
	
	//加载已经绑定了的门牌号
	$.loy.ajax({
		url : "/mp/loadBindDoorplate",
		type : 'GET',
		data : {
			proprietorId : $("#proprietorId").val()
		},
		success : function(data) {
			var result=data.data;
			for (var i = 0; i < result.length; i++) {
				var option=$("<option></option>");
				option.val(result[i].id);
				option.text(result[i].doorplateNo);
				option.attr("selected","selected");
				$('#duallist').append(option);
			}
			doorplateBox = $('#duallist').bootstrapDualListbox();
			doorplateContainer = doorplateBox.bootstrapDualListbox('getContainer');
			doorplateContainer.find('.btn').addClass('btn-white btn-info btn-bold');
		},
		error : function(data){
		}
	})
   $('#doorplateBindDiv', $proprietorContainer).modal("show");
}
function refreshGrid(){
	proprietorGrid.jqGrid().trigger("reloadGrid");
}

function initProprietorDropzone(muban){
	ProprietorDropzone = new Dropzone("#proprietordropzone",{
	    url : "/sys/img/upload", //必须填写
	    method : "post", //也可用put
	    paramName : "file", //默认为file 
	    headers : $.loy.token(),
	    maxFiles : 10,//一次性上传的文件数量上限
	    maxFilesize : 20, //MB
	    acceptedFiles : ".jpg,.gif,.png", //上传的类型  
	    dictDefaultMessage : "",
	    dictMaxFilesExceeded : "一次只能上传10张图片!",
	    addRemoveLinks : false,
	    clickable : ".fileinput-button", // 点击某个按钮或区域后出现选择电脑中本地图片，默认是previewsContainer指定的区域
	    previewTemplate : muban,//设置显示模板,					    
	    init : function() {

		MDropzone = this;

		this.on("removedfile", function(file) {
		});

		this.on("addedfile", function(file) {
		    //上传文件时触发的事件
		    file.previewElement.querySelector('[data-rel]').setAttribute('id', file.id);
		    file.previewElement.querySelector('[data-rel]').setAttribute('href', file.httpurl);

		});

		this.on("queuecomplete", function() {
		    $('.dropzone [data-rel="colorbox"]').colorbox(colorbox_params);
		});

		this.on("success", function(file, data) {
		    //上传完成后触发的方法	    
		    file.previewElement.querySelector('[data-rel]').setAttribute('id', data.data.obj.id);
		    file.previewElement.querySelector('[data-rel]').setAttribute('href', data.data.obj.httpurl);

		});
		this.on("error", function(file, message) {
		    //this.removeFile(file);  
		    //$.loy.alert(message.data ? message.data.error : message,'error');	
		    $(file.previewElement).find('[data-dz-errormessage]').html(message.data ? message.data.error : message);
		});
	    }

	});
}
</script>